import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/entity/selectiont_entity.dart';
import 'package:shopping_group/entity/task_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/more/bloc/video_bloc.dart';
import 'package:shopping_group/modle/more/entity/group_detail_entity.dart';
import 'package:shopping_group/modle/more/ui/video_page.dart';
import 'package:shopping_group/modle/person/bloc/my_money_bloc.dart';
import 'package:shopping_group/modle/play/bloc/pingtuan_play_bloc.dart';
import 'package:shopping_group/modle/play/entity/user_account_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/ad_video_util.dart';
import 'package:shopping_group/utils/log_util.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';
import 'package:bot_toast/bot_toast.dart';
import 'pingtuan_play_ok_page.dart';

class PingtuanPalyPage extends StatefulWidget {
  final GroupDetailEntity entity;
  PingtuanPalyPage({Key key, this.entity}) : super(key: key);

  @override
  _PingtuanPalyPageState createState() => _PingtuanPalyPageState();
}

class _PingtuanPalyPageState extends State<PingtuanPalyPage> {
  List<TaskEntity> _selectList = [];
  PingtuanPlayBloc _bloc;
  MyMoneyBloc _myMoneyBloc;
  UserAccountEntity _entity = UserAccountEntity();
  StreamSubscription _goViewSubscription;
  StreamSubscription _zfbStartListSubscription;
  StreamSubscription _zfbCallblackListSubscription;
  StreamSubscription _zfbCompleteListSubscription;
  StreamSubscription _validateSubscription;
  StreamSubscription _videoCompletetSubscription;
  StreamSubscription _videoXYCloseSubscription;
  String _lastJoin = '';
  SelectiontEntity _selection = SelectiontEntity();
  DateTime lastPopTime;
  VideoBloc _videoBloc;
  @override
  void initState() {
    super.initState();
    _bloc = PingtuanPlayBloc();
    _myMoneyBloc = MyMoneyBloc();
    _myMoneyBloc.initDate.add(null);
    _videoBloc = VideoBloc();
    bool notye =
        ObjectUtil.isEmptyString(this.widget.entity.thisGroupAcctVal) ||
                '0.00' == this.widget.entity.thisGroupAcctVal
            ? true
            : double.parse(
                    ObjectUtil.isEmptyString(this.widget.entity.realCharge)
                        ? '0'
                        : this.widget.entity.realCharge) >
                double.parse(this.widget.entity.thisGroupAcctVal);

    bool nbzf = double.parse(
            ObjectUtil.isEmptyString(this.widget.entity.thisGroupAcctVal)
                ? '0'
                : this.widget.entity.thisGroupAcctVal) >=
        double.parse(this.widget.entity.realCharge);
    if (!nbzf) {
      _selectList
        ..add(TaskEntity()
          ..id = '1'
          ..title = '支付宝支付'
          ..url = 'http://static.jiujiupingou.com/Static/img/bg23.png'
          ..isCilke = notye);
    }
    _selectList
      ..add(TaskEntity()
        ..id = '2'
        ..title = '代理券总余额 ¥${BaseConstant.capitalAccount}'
        ..content =
            '本任务可用代理券余额 ¥${ObjectUtil.isEmptyString(this.widget.entity.thisGroupAcctVal) ? '0.00' : this.widget.entity.thisGroupAcctVal}'
        ..url = 'http://static.jiujiupingou.com/Static/img/bg21.png'
        ..isCilke = !notye);

    _videoCompletetSubscription =
        eventBus.on<AvCompleteEvent>().listen((event) {
      if (!mounted) {
        return;
      }

      Map<String, dynamic> data = {};
      data['groupSpecId'] = this.widget.entity.groupSpecId;
      data['myLastJoinId'] = _lastJoin;
      data['userId'] = BaseConstant.userId;
      _videoBloc.initPlayDate.add(data);
    });

    _goViewSubscription = eventBus.on<PlayPingtuanOkEvent>().listen((event) {
      // if (!ObjectUtil.isEmptyString(this.widget.entity.playXiYi) &&
      //     'Y' == this.widget.entity.playXiYi) {
      //   BotToast.showLoading();
      //   AdVideoUtil.startVd('rv1');
      // } else {
      RouteUtil.popUntil(PageConstance.MAIN_PAGE);
      this.widget.entity.joinId = _lastJoin;
      RouteUtil.goParameter(PingtuanPlayokPage(
        entity: this.widget.entity,
      ));
      RouteUtil.goParameter(VideoPage(
          groupSpecId: this.widget.entity.groupSpecId,
          myLastJoinId: _lastJoin,
          videoUrl: this.widget.entity.failSeeVideoUrl));
      // }
    });

    _zfbCompleteListSubscription =
        eventBus.on<ZfbPingtuanCompeteEvent>().listen((event) {
      // if (!ObjectUtil.isEmptyString(this.widget.entity.playXiYi) &&
      //     'Y' == this.widget.entity.playXiYi) {
      //   BotToast.showLoading();
      //   AdVideoUtil.startVd('rv1');
      // } else {
      RouteUtil.popUntil(PageConstance.MAIN_PAGE);
      this.widget.entity.joinId = _lastJoin;
      RouteUtil.goParameter(PingtuanPlayokPage(
        entity: this.widget.entity,
      ));
      RouteUtil.goParameter(VideoPage(
          groupSpecId: this.widget.entity.groupSpecId,
          myLastJoinId: _lastJoin,
          videoUrl: this.widget.entity.failSeeVideoUrl));
      // }
    });

    _videoXYCloseSubscription = eventBus.on<XiYuAvCloseEvent>().listen((event) {
      BotToast.closeAllLoading();
      RouteUtil.popUntil(PageConstance.MAIN_PAGE);
      this.widget.entity.joinId = _lastJoin;
      RouteUtil.goParameter(PingtuanPlayokPage(
        entity: this.widget.entity,
      ));
    });

    _zfbCallblackListSubscription =
        eventBus.on<ZfbCallbackEvent>().listen((event) {
      _completeVide(BaseConstant.PO_ZI_FU_BAO);
    });

    _validateSubscription =
        eventBus.on<ValidatePingtuanEvent>().listen((event) {
      _lastJoin = event.lastJoinId;
      _completeVide(BaseConstant.PO_INNER);
    });

    _zfbStartListSubscription =
        eventBus.on<ZfbPingtuanStartEvent>().listen((event) {
      Map<String, dynamic> data = {};
      _lastJoin = event.joinId;
      data['id'] = _lastJoin;
      data['name'] = '订单：$_lastJoin';
      data['price'] = event.price;
      data['joinId'] = _lastJoin;
      data['type'] = BaseConstant.PINGTUAN_TYPE;
      data['userId'] = BaseConstant.userId;
      data['groupSpecId'] = this.widget.entity.groupSpecId;
      data['payVal'] = this.widget.entity.realCharge;
      data['custGroupsRelaId'] = this.widget.entity.custGroupSpecRelaId;
      data['payUuid'] = this.widget.entity.payUuid;
      data['payOption'] = BaseConstant.PO_ZI_FU_BAO;
      data['appOrWeb'] = 'WEB';
      data['orderName'] = this.widget.entity.name;
      data['payType'] = 'PT_ZFB';
      _bloc.zfbPlayDate.add(data);
      LogUtil.e(data.toString(),
          tag: "_zfbStartListSubscription.........../////////////////");
    });

    _selection = SelectiontEntity()
      ..title = '同意利正分销代理合同'
      ..isSelect = true;
  }

  _completeVide(String payOption) {
    Map<String, dynamic> data = {};
    data['joinId'] = _lastJoin;
    data['userId'] = BaseConstant.userId;
    data['name'] = this.widget.entity.name;
    data['groupSpecId'] = this.widget.entity.groupSpecId;
    data['payVal'] = this.widget.entity.realCharge;
    data['custGroupsRelaId'] = this.widget.entity.custGroupSpecRelaId;
    data['payUuid'] = this.widget.entity.payUuid;
    data['payOption'] = payOption;
    _bloc.playCompleteDate.add(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '提交代理券'),
      body: Container(
        height: double.infinity,
        decoration: new BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: 32,
                  ),
                  _moneyView(),
                  SizedBox(
                    height: 8,
                  ),
                  _selectView(),
                  SizedBox(
                    height: 8,
                  ),
                  _showXyView(_selection),
                  SizedBox(
                    height: 8,
                  ),
                  Expanded(child: _contentView()),
                  SizedBox(
                    height: 8,
                  ),
                ],
              ),
            ),
            ButtonProgressView.crateCupertinoView('确认提交代理券',
                blackColor: Colours.main_01, cupertinoCall: () {
              if (null != lastPopTime &&
                  DateTime.now().difference(lastPopTime) <=
                      Duration(milliseconds: 500)) {
                lastPopTime = DateTime.now();
                BotToast.showText(text: '连续点击过快');
                return;
              } else {
                lastPopTime = DateTime.now();
              }
              if (!_selection.isSelect) {
                BotToast.showText(text: '请同意利正分销代理合同');
                return;
              }
              _selectList.forEach((element) {
                bool notye = double.parse(
                        ObjectUtil.isEmptyString(this.widget.entity.realCharge)
                            ? '0'
                            : this.widget.entity.realCharge) >
                    double.parse(this.widget.entity.thisGroupAcctVal);
                if (element.isCilke && '2' == element.id && notye) {
                  BotToast.showText(text: '可用余额不足');
                  return;
                } else if (element.isCilke &&
                    ('1' == element.id || '2' == element.id)) {
                  _zfBloc(element);
                  return;
                }
              });
            }),
            SizedBox(
              height: 32,
            ),
          ],
        ),
      ),
    );
  }

  Widget _contentView() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.symmetric(horizontal: Dimens.FONT_SIZE_8),
      padding: EdgeInsets.symmetric(
          vertical: Dimens.FONT_SIZE_12, horizontal: Dimens.FONT_SIZE_16),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 0.0),
          borderRadius: BorderRadius.circular(10.0),
          color: Colours.title_white),
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        reverse: false,
        padding: EdgeInsets.all(0.0),
        physics: BouncingScrollPhysics(),
        child: WidgetUtils.getTextColorView(
          BaseConstant.CONTEN_DL,
          Colours.text_2222,
          Dimens.FONT_SIZE_14,
          // textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Widget _showXyView(SelectiontEntity entity) {
    return WidgetUtils.getCheckboxIocnView(entity,
        textColor: Colours.gray_33, iconsColor: Colours.gray_33, blackCall: () {
      setState(() {
        entity.isSelect = !entity.isSelect;
      });
    }, verticalPadding: 0);
  }

  _zfBloc(element) {
    Map<String, dynamic> data = {};
    data['userId'] = BaseConstant.userId;
    data['name'] = this.widget.entity.name;
    data['groupSpecId'] = this.widget.entity.groupSpecId;
    data['payVal'] = this.widget.entity.realCharge;
    data['payOption'] = (element.isCilke && '1' == element.id)
        ? BaseConstant.PO_ZI_FU_BAO
        : BaseConstant.PO_INNER;
    data['custGroupsRelaId'] = this.widget.entity.custGroupSpecRelaId;
    data['payUuid'] = this.widget.entity.payUuid;
    _bloc.validateDate.add(data);
  }

  Widget _selectView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: Column(
        children: <Widget>[
          WidgetUtils.getTextColorView(
              '选择支付方式', Colours.text_2222, Dimens.FONT_SIZE_18),
          SizedBox(
            height: 16,
          ),
          _selectFsView(),
        ],
      ),
    );
  }

  Widget _selectFsView() {
    return StreamBuilder(
      stream: _myMoneyBloc.sendAllData,
      initialData: _entity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is UserAccountEntity) {
          _entity = object;
        }

        _selectList.forEach((element) {
          if ('2' == element.id) {
            element.title = '代理券总余额 ¥${_entity.capitalAccount}';
          }
        });

        return Column(
          children: _selectList.map((TaskEntity entity) {
            bool isEnd = _selectList[_selectList.length - 1].id == entity.id;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectList.forEach((element) {
                    element.isCilke = false;
                  });
                  entity.isCilke = true;
                });
              },
              child: Container(
                color: Colours.transparent,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: Row(
                          children: <Widget>[
                            WidgetUtils.buildNetworkImageView(entity.url,
                                width: 24, height: 24),
                            SizedBox(
                              width: 8,
                            ),
                            WidgetUtils.getTextColorView(
                                ObjectUtil.isEmptyString(entity.content)
                                    ? entity.title
                                    : '${entity.title} \n${entity.content}',
                                Colours.text_2222,
                                Dimens.FONT_SIZE_14),
                          ],
                        )),
                        Icon(
                          entity.isCilke
                              ? Icons.radio_button_checked
                              : Icons.radio_button_unchecked,
                          color: entity.isCilke
                              ? Colours.themeColor
                              : Colours.gray_f0,
                          size: 24,
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    isEnd ? Container() : WidgetUtils.drawCodeDivider(),
                    isEnd
                        ? Container()
                        : SizedBox(
                            height: 12,
                          ),
                  ],
                ),
              ),
            ); //赋值后的Widget
          }).toList(),
        );
      },
    );
  }

  Widget _moneyView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: WidgetUtils.getTextColorView('¥ ${this.widget.entity.realCharge}',
          Colours.text_2222, Dimens.FONT_SIZE_30),
    );
  }

  @override
  void dispose() {
    _videoXYCloseSubscription?.cancel();
    _goViewSubscription?.cancel();
    _zfbStartListSubscription?.cancel();
    _zfbCompleteListSubscription?.cancel();
    _zfbCallblackListSubscription?.cancel();
    _validateSubscription?.cancel();
    _videoCompletetSubscription?.cancel();
    super.dispose();
  }
}
